package app

import (
	"github.com/olivere/elastic/v7"
	"go-demo/common/global"
	"log"
	"os"
)

type ElasticSearch struct{}

func (es ElasticSearch) Load() {
	client := connectES()
	global.App.Elastic = client
}

func connectES() *elastic.Client {
	// elasticsearch 配置
	var (
		url     = global.App.Config.ElasticConfig.Url
		sniff   = global.App.Config.ElasticConfig.Sniff
		health  = global.App.Config.ElasticConfig.HealthCheckInterval
		errlog  = global.App.Config.ElasticConfig.ErrLog
		infolog = global.App.Config.ElasticConfig.InfoLog
	)

	var err error
	client, err := elastic.NewClient(
		// 设置Elastic服务地址
		elastic.SetURL(url),
		// 是否转换请求地址，默认为true,当等于true时 请求http://ip:port/_nodes/http，将其返回的url作为请求路径
		elastic.SetSniff(sniff),
		// 心跳检查,间隔时间
		elastic.SetHealthcheckInterval(health),
		// 设置错误日志
		elastic.SetErrorLog(log.New(os.Stderr, errlog, log.LstdFlags)),
		// 设置info日志
		elastic.SetInfoLog(log.New(os.Stdout, infolog, log.LstdFlags)),
	)
	if err != nil {
		log.Panic("elasticsearch 连接出现错误~~~", err)
	}
	log.Println("elasticsearch数据库连接成功", client)

	return client
}
